<template>
  <XenPageLayout
    title="加班申请详情"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
    :loading="loading"
    :error="hasError"
    @retry="loadOvertimeDetail(Id)"
  >
    <!-- 内容区域 -->
    <view
      class="details-container"
      :class="{ 'has-audit-actions': isMyApprove }"
    >
      <!-- 详情内容 -->
      <view class="details-card">
        <view class="card-content">
          <!-- 使用动态详情组件 -->
          <XenDynamicDetailsCard
            :sections="formSections"
            :data="processedData"
            :field-mapping="fieldMapping"
            :get-image-url="getImageUrl"
            @preview-image="previewImage"
          />

          <!-- 审核时间线组件 - 所有用户都有权限查看 -->
          <XenAuditTimeline :steps="timelineData" />
        </view>
      </view>
    </view>

    <!-- 审核操作按钮组件 - 根据IsMyApprove字段控制显示 -->
    <XenAuditActions
      v-if="isMyApprove"
      ref="auditActionsRef"
      :actions="auditActions"
      @action="handleAuditAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicDetailsCard from "@/components/XenDynamicDetailsCard.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import XenAuditActions from "@/components/XenAuditActions.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useOvertimeInfo } from "./composables/useInfo";

import commonApi from "@/api/common";
import SysDailyOvertimeRequestBillApi from "./api/index";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";
import type { ISysDailyOvertimeRequestBillVm, ISearchByPersonRequest } from "./api/interface";
import type { ICompanyItem } from "@/type/common";

// 获取详情页面的表单分组配置
const formSections = computed(() => getFormSectionsByPageType("details"));

// 页面状态
const Id = ref<string>("");
const hasError = ref<boolean>(false);

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);
const isMyApprove = ref<boolean>(false);
const auditLoading = ref<boolean>(false);
const auditActionsRef = ref();

// 公司和部门数据
const companyList = ref<ICompanyItem[]>([]);
const departmentList = ref<any[]>([]);

// 排班记录选项数据
const scheduleRecordOptions = ref<any[]>([]);

// 处理原始数据，将OrgId转换为公司名称，GroupId转换为部门名称
const processedData = computed(() => {
  if (!originalData.value) return null;

  const data = { ...originalData.value };

  // 如果有OrgId，将公司名称设置给Org.Name字段用于显示
  if (data.OrgId) {
    const companyName = getCompanyNameById(data.OrgId);
    if (companyName) {
      // 确保Org对象存在
      if (!data.Org) {
        data.Org = {};
      }
      // 设置公司名称到Org.Name，这样fieldMapping中的"Org.Name"就能获取到值
      data.Org.Name = companyName;
    }
  }

  // 如果有GroupId，将部门名称设置给Group.GroupName字段用于显示
  if (data.GroupId) {
    const departmentName = getDepartmentNameById(data.GroupId);
    if (departmentName) {
      // 确保Group对象存在
      if (!data.Group) {
        data.Group = {};
      }
      // 设置部门名称到Group.GroupName，这样fieldMapping中的"Group.GroupName"就能获取到值
      data.Group.GroupName = departmentName;
    }
  }

  // 如果有RecordId，将排班记录文字设置给RecordText字段用于显示
  if (data.RecordId) {
    const recordText = getScheduleRecordTextById(data.RecordId);
    if (recordText) {
      // 设置排班记录文字，用于详情页显示
      data.RecordText = recordText;
    }
  }

  return data;
});

// 创建API实例
const commonApiInstance = commonApi();
const api = SysDailyOvertimeRequestBillApi();

// 使用加班申请信息 Composable
const {
  loading,
  originalData,
  getImageUrl,
  initializeOptions,
  loadOvertimeDetail,
  fieldMapping,
} = useOvertimeInfo();

// 根据公司ID获取公司名称
const getCompanyNameById = (orgId: string | null): string => {
  if (!orgId || !companyList.value.length) return "";

  const company = companyList.value.find((item) => item.Value === orgId);
  return company ? company.Text : "";
};

// 根据部门ID获取部门名称（递归查找，支持多级部门）
const getDepartmentNameById = (groupId: string | null): string => {
  if (!groupId || !departmentList.value.length) return "";

  // 递归查找部门
  const findDepartmentById = (departments: any[], id: string): any => {
    for (const dept of departments) {
      if (dept.ID === id || dept.Value === id) {
        return dept;
      }
      if (dept.Children && dept.Children.length > 0) {
        const found = findDepartmentById(dept.Children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const department = findDepartmentById(departmentList.value, groupId);
  return department
    ? department.Text || department.GroupName || department.Name
    : "";
};

// 根据排班记录ID获取排班记录文字
const getScheduleRecordTextById = (recordId: string | null): string => {
  if (!recordId || !scheduleRecordOptions.value.length) return "";

  const record = scheduleRecordOptions.value.find(
    (option: any) => option.value === recordId
  );
  return record ? record.text : "";
};

// 加载公司列表
const loadCompanyList = async () => {
  const response = await commonApiInstance.GetUserCompanies();
  if (response && Array.isArray(response)) {
    companyList.value = response;
  }
};

// 加载部门列表
const loadDepartmentList = async () => {
  const response = await commonApiInstance.GetParentsTree();
  if (response && Array.isArray(response)) {
    departmentList.value = response;
  }
};

// 加载排班记录选项数据
const loadScheduleRecordOptions = async (personId: string) => {
  if (!personId) return;

  try {
    // 构建查询参数
    const today = new Date();
    const startDate = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000)
      .toISOString()
      .split("T")[0];
    const endDate = today.toISOString().split("T")[0];

    const params: ISearchByPersonRequest = {
      PersonId: personId,
      Page: 1,
      Limit: 100,
      IsPlainText: true,
      IsEmunToString: true,
      ShiftDate: [startDate, endDate],
    };

    const response = await api.searchByPerson(params);

    if (
      response &&
      response.Data &&
      response.Data[0] &&
      response.Data[0].Records &&
      Array.isArray(response.Data[0].Records)
    ) {
      // 过滤掉AttendanceResult为"未计算"的数据
      const filteredRecords = response.Data[0].Records.filter((item: any) => 
        item.AttendanceResult !== "未计算"
      );
      
      scheduleRecordOptions.value = filteredRecords.map((item: any) => ({
        value: item.ID || item.Id,
        text: `${item.ShiftDate || ""} ${item.AttendanceShiftGroupName || ""} (${item.ShiftInfo || ""})`,
      }));
    }
  } catch (error) {
    console.error("加载排班记录选项失败:", error);
  }
};

// 审核操作按钮配置
const auditActions = computed(() => [
  {
    key: "approve",
    label: "同意",
    type: "primary" as const,
    icon: "checkmarkempty",
    primary: true,
    customStyle: "background: #409eff; color: #ffffff;",
    disabled: auditLoading.value,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger" as const,
    icon: "closeempty",
    primary: true,
    customStyle: "background: #f56c6c; color: #ffffff;",
    disabled: auditLoading.value,
  },
]);

// 获取时间线数据
const getTimelineData = async () => {
  if (!Id.value) return;

  try {
    const queryParams: QueryTimeline = {
      TableName: "SysDailyOvertimeRequestBill",
      DataId: Id.value,
    };

    const response = await commonApiInstance.GetWorkflowInfo(queryParams);
    if (response && Array.isArray(response)) {
      timelineData.value = response;
    }
  } catch (error) {
    console.error("获取时间线数据失败:", error);
  }
};

// 图片预览
const previewImage = (urls: string[], current: string) => {
  uni.previewImage({
    urls,
    current,
  });
};

// 审核操作处理
const handleAuditAction = async (action: any) => {
  if (!originalData.value) return;

  auditLoading.value = true;

  try {
    let actionName = "";
    let confirmTitle = "";
    let confirmContent = "";

    switch (action.key) {
      case "approve":
        actionName = "Approve";
        confirmTitle = "确认同意";
        confirmContent = "确定要同意这个加班申请吗？";
        break;
      case "reject":
        actionName = "Reject";
        confirmTitle = "确认拒绝";
        confirmContent = "确定要拒绝这个加班申请吗？";
        break;
      default:
        auditLoading.value = false;
        return;
    }

    // 显示确认对话框
    const confirmed = await new Promise<boolean>((resolve) => {
      uni.showModal({
        title: confirmTitle,
        content: confirmContent,
        success: (res) => {
          resolve(res.confirm);
        },
        fail: () => {
          resolve(false);
        },
      });
    });

    if (!confirmed) {
      auditLoading.value = false;
      return;
    }

    // 如果是拒绝操作，需要输入拒绝理由
    let remark = "";
    if (action.key === "reject") {
      remark = await auditActionsRef.value?.getRejectReason();
      if (!remark) {
        auditLoading.value = false;
        return;
      }
    }

    // 构建审核数据
    const auditData: ISysDailyOvertimeRequestBillVm = {
      Entity: originalData.value,
      ActionName: actionName,
      IsMyApprove: isMyApprove.value,
      Remark: remark,
    };

    // 调用审核接口
    const response = await api.approve(auditData);

    if (response && response.ID) {
      uni.showToast({
        title: action.key === "approve" ? "审核通过" : "已拒绝",
        icon: "success",
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        },
      });
    } else {
      uni.showToast({
        title: "操作失败，请重试",
        icon: "none",
        duration: 2000,
      });
    }
  } catch (error) {
    console.error("审核操作失败:", error);
    uni.showToast({
      title: "操作失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    auditLoading.value = false;
  }
};

// 页面加载
onMounted(async () => {
  await initializeOptions();
  await loadCompanyList();
  await loadDepartmentList();
});

// 路由参数处理
onLoad(async (options: any) => {
  if (options.id) {
    Id.value = options.id;

    try {
      hasError.value = false;
      await loadOvertimeDetail(options.id);

      // 如果有员工ID，加载排班记录选项数据
      if (originalData.value?.PersonId) {
        await loadScheduleRecordOptions(originalData.value.PersonId);
      }

      // 检查是否有审核权限
      if (originalData.value) {
        // 这里需要根据实际业务逻辑判断是否有审核权限
        // 暂时设置为false，实际应该根据后端返回的数据判断
        isMyApprove.value = false;
      }

      // 获取时间线数据
      await getTimelineData();
    } catch (error) {
      console.error("加载详情失败:", error);
      hasError.value = true;
    }
  }
});

// 分享配置
onShareAppMessage(() => {
  return {
    title: "加班申请详情",
    path: `/subpkg-daily-sysdailyovertimerequestbill/details?id=${Id.value}`,
  };
});
</script>

<style lang="scss" scoped>
.details-container {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 80px);

  &.has-audit-actions {
    padding-bottom: calc(92px + constant(safe-area-inset-bottom));
    padding-bottom: calc(92px + env(safe-area-inset-bottom));
  }
}

.details-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card-content {
  padding: 24px;
}
</style>
